//
//  InputView.m
//  ECBBusinessCamp
//
//  Created by rimi on 16/6/22.
//  Copyright © 2016年 邓毕华. All rights reserved.
//

#import "InputView.h"

#import "EmojiView.h"
#import <AVFoundation/AVFoundation.h>
#import "lame.h"

#define kRecordAudioFile @"myRecord.caf"

@interface InputView ()

@property (nonatomic, strong) NSString * HighlightedImageName; // 高度状态图片名称
@property (nonatomic, strong) NSArray * emojiArray; // 表情数组
@property (nonatomic, strong) AVAudioRecorder * audioRecorder; // 录音机
@property (nonatomic, strong) NSTimer *timer;// 录音声波监控
@property (nonatomic, assign) NSInteger seconds; // 录音时长

@end

@implementation InputView

#pragma mark 🌷🌷🌷life cycle🌷🌷🌷
- (instancetype)initWithClickRefreshBlock:(ClickRefreshBlock)clickRefreshBlock
{
    self = [super init];
    if (self) {
        _clickRefreshBlock = clickRefreshBlock;
        self.backgroundColor = RGB_COLOR(239, 239, 239, 1);
        
        // 第一次是文字输入的高亮图片
        _HighlightedImageName = @"chat_voice_s.png";
        
        // 添加视图
        [self addSubview:self.inputTypeButton];
        [self addSubview:self.inputTextField];
        [self addSubview:self.commentButton];
        [self addSubview:self.expressionButton];
        
        // 自动布局
        [_inputTypeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(self).multipliedBy(0.8);
            make.width.equalTo(self).multipliedBy(0.1);
            make.centerY.equalTo(self);
            make.left.offset(SCREEN_WIDTH * 0.005);
        }];
        [_inputTextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(self).multipliedBy(0.84);
            make.width.equalTo(self).multipliedBy(0.74);
            make.centerY.equalTo(self);
            make.left.equalTo(_inputTypeButton.mas_right).offset(SCREEN_WIDTH * 0.002);
        }];
        [_commentButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.equalTo(_inputTypeButton);
            make.centerY.equalTo(self);
            make.left.equalTo(_inputTextField.mas_right).offset(SCREEN_WIDTH * 0.002);
        }];
        [_expressionButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.equalTo(_inputTypeButton.mas_height);
            make.centerY.equalTo(self);
            make.right.offset(SCREEN_WIDTH * -0.003);
        }];
    }
    return self;
}

#pragma mark 🌷🌷🌷event responds🌷🌷🌷
- (void)respondsToInputBtn:(UIButton *)sender {
    _inputTextField.inputView = nil;
    [_inputTextField resignFirstResponder];
    // current voice
    NSString *normalImage = @"chat_voice.png";
    if ([_HighlightedImageName isEqualToString:@"chat_voice_s.png"]) {
        normalImage = @"chat_text.png";
        _HighlightedImageName = @"chat_text_s.png";
        
        // 添加录音按钮
        [self addSubview:self.inputButton];
        
        // 自动布局
        [_inputButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.equalTo(_inputTextField);
            make.center.equalTo(_inputTextField);
        }];
        
        [_inputTextField resignFirstResponder];
    }else{
        _HighlightedImageName = @"chat_voice_s.png";
        
        [_inputButton removeFromSuperview];
        [_inputTextField becomeFirstResponder];
    }
    [_inputTypeButton setImage:[UIImage imageNamed:normalImage] forState:UIControlStateNormal];
    [_inputTypeButton setImage:[UIImage imageNamed:_HighlightedImageName] forState:UIControlStateHighlighted];
}
- (void)respondsToExpressionButton {
    [_inputButton removeFromSuperview];
    EmojiView * emojiView = [[EmojiView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT * 0.33) selecEmojiIndexBlock:^(NSInteger index) {
        if (index == -1) {
            [_inputTextField deleteBackward];
        } else {
            _inputTextField.text = [NSString stringWithFormat:@"%@%@", _inputTextField.text, self.emojiArray[index]];
        }
    }];
    if (_inputTextField.inputView != emojiView) {
        [_inputTextField resignFirstResponder];
        _inputTextField.inputView = emojiView;
        [_inputTextField becomeFirstResponder];
    }
    
    // 设置输入类型按钮
    _HighlightedImageName = @"chat_text_s.png";
    [_inputTypeButton setImage:[UIImage imageNamed:@"chat_text.png"] forState:UIControlStateNormal];
    [_inputTypeButton setImage:[UIImage imageNamed:@"chat_text_s.png"] forState:UIControlStateHighlighted];
}
- (void)respondsToCommentBtn {
    if (_inputTextField.text.length == 0) {
        [MBProgressHUD showError:@"发送内容不能为空"];
        return;
    }
    // 发送评论
    NSMutableDictionary * parameters = [NSMutableDictionary dictionary];
    [parameters setObject:_id forKey:@"comid"];
    [parameters setObject:[NSString getStringForEmojiString:_inputTextField.text] forKey:@"content"];
    [parameters setObject:_msgTo != nil ? _msgTo : _id forKey:@"msgTo"];
    [parameters setObject:[LoginUserInfo defaultUserInfo].userid forKey:@"uid"];
    [parameters setObject:@"" forKey:@"voice"];
    
    [[NetTool sharedTool] requestMethod:POST loadingMsg:@"发送中..." url:BASEURLAPPEND(COMMUNITYINTERACTIONCOMMIT_URL) parameters:parameters finish:^(id responseObject, NSError *error) {
        if (!error) {
            if ([responseObject[@"status"] integerValue] == 1) {
                [MBProgressHUD showSuccess:responseObject[@"data"]];
                
                // 刷新表格视图
                _clickRefreshBlock();
            } else {
                [MBProgressHUD showError:responseObject[@"data"]];
            }
        } else {
            [MBProgressHUD showError:[[NSString stringWithFormat:@"%@", error] containsString:@"The request timed out."] ? @"登录超时" : @"I don't know"];
        }
    }];
}
- (void)respondsToRecoderStart {
    if (![self.audioRecorder isRecording]) {
        [self.audioRecorder record];
        _seconds = 0;
        self.timer.fireDate=[NSDate distantPast];
    }
}
- (void)respondsToRecoderStop {
    [self.audioRecorder stop];
    self.timer.fireDate=[NSDate distantFuture];

    if (_seconds < 2) {
        [MBProgressHUD showError:@"录音时间太短"];
        return;
    }
    NSString * urlStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString * cafFielPath = [urlStr stringByAppendingPathComponent:kRecordAudioFile];
    
    NSString * mp3FilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/myRecord.mp3"];
    [self converCafFileToMP3FileAtPath:cafFielPath toPath:mp3FilePath];
    NSData * data = [NSData dataWithContentsOfFile:mp3FilePath];
    
    NSMutableDictionary * parameters = [NSMutableDictionary dictionary];
    [parameters setObject:_id forKey:@"comid"];
    [parameters setObject:@"" forKey:@"content"];
    [parameters setObject:_msgTo != nil ? _msgTo : _id forKey:@"msgTo"];
    [parameters setObject:[LoginUserInfo defaultUserInfo].userid forKey:@"uid"];
    [parameters setObject:@"" forKey:@"voice"];
    
    NSMutableDictionary * fileDic = [NSMutableDictionary dictionary];
    //data
    fileDic[@"data"] = data;
    //字段名
    fileDic[@"key"] = @"voice";
    fileDic[@"fileName"] = @"myRecord.mp3";
    fileDic[@"dataType"] = @"audio/mpeg";
    
    [[NetTool sharedTool] requestMethod:POST loadingMsg:@"发送中..." url:BASEURLAPPEND(COMMUNITYINTERACTIONCOMMIT_URL) otherData:fileDic parameters:parameters finish:^(id responseObject, NSError *error) {
        if (!error) {
            if ([responseObject[@"status"] integerValue] == 1) {
                [MBProgressHUD showSuccess:responseObject[@"评论成功"]];
                
                // 刷新表格视图
                _clickRefreshBlock();
            } else {
                [MBProgressHUD showError:responseObject[@"error"]];
            }
        } else {
            [MBProgressHUD showError:[[NSString stringWithFormat:@"%@", error] containsString:@"The request timed out."] ? @"登录超时" : @"I don't know"];
        }
    }];
}

#pragma mark 🌷🌷🌷private methods🌷🌷🌷
-(NSURL *)getSavePath{
    NSString * urlStr=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    urlStr = [urlStr stringByAppendingPathComponent:kRecordAudioFile];
    NSURL * url = [NSURL fileURLWithPath:urlStr];
    return url;
}
-(NSDictionary *)getAudioSetting{
    NSMutableDictionary *dicM=[NSMutableDictionary dictionary];
    //设置录音格式
    [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
    //设置录音采样率，8000是电话采样率，对于一般录音已经够了
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    //设置通道,这里采用单声道
    [dicM setObject:@(1) forKey:AVNumberOfChannelsKey];
    //每个采样点位数,分为8、16、24、32
    [dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];
    //是否使用浮点数采样
    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    //....其他设置等
    return dicM;
}
-(NSTimer *)timer{
    if (!_timer) {
        _timer=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(audioPowerChange) userInfo:nil repeats:YES];
    }
    return _timer;
}
- (void)audioPowerChange{
    _seconds += 1;
}
- (void)converCafFileToMP3FileAtPath:(NSString *)cafPath toPath:(NSString *)mp3FilePath
{
    
    @try {
        int read, write;
        
        FILE * pcm = fopen([cafPath cStringUsingEncoding:1], "rb");//被转换的文件
        FILE * mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");//转换后文件的存放位置
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE*2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, 8000);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            unsigned long size_t = 2*sizeof(short int);
            read = fread(pcm_buffer, size_t, PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            fwrite(mp3_buffer, write, 1, mp3);
        } while (read != 0);
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException *exception) {
        //        NSLog(@"%@",[exception description]);
    }
    @finally {
        NSError * error = nil;
        [[NSFileManager defaultManager]removeItemAtPath:cafPath error: &error];
        if (error) {
            //            NSLog(@"Remove CAF file Failed.");
        }
    }
}

#pragma mark 🌷🌷🌷getters and setters🌷🌷🌷
- (UIButton *)inputTypeButton {
    if (!_inputTypeButton) {
        _inputTypeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_inputTypeButton setImage:[UIImage imageNamed:@"chat_voice.png"] forState:UIControlStateNormal];
        [_inputTypeButton setImage:[UIImage imageNamed:_HighlightedImageName] forState:UIControlStateHighlighted];
        [_inputTypeButton addTarget:self action:@selector(respondsToInputBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _inputTypeButton;
}
- (UITextField *)inputTextField {
    if (!_inputTextField) {
        _inputTextField = [[UITextField alloc] init];
        _inputTextField.font = [UIFont systemFontOfSize:20];
        _inputTextField.borderStyle = UITextBorderStyleBezel;
    }
    return _inputTextField;
}
- (UIButton *)inputButton {
    if (!_inputButton) {
        _inputButton = [[UIButton alloc] init];
        [_inputButton setImage:[UIImage imageNamed:@"chat_voiceInput.png"] forState:UIControlStateNormal];
        [_inputButton setImage:[UIImage imageNamed:@"chat_voiceInput_s.png"] forState:UIControlStateHighlighted];
        [_inputButton addTarget:self action:@selector(respondsToRecoderStart) forControlEvents:UIControlEventTouchDown];
        [_inputButton addTarget:self action:@selector(respondsToRecoderStop) forControlEvents:UIControlEventTouchUpInside];
    }
    return _inputButton;
}
- (UIButton *)commentButton {
    if (!_commentButton) {
        _commentButton = [[UIButton alloc] init];
        [_commentButton setImage:[UIImage imageNamed:@"chat_publish.png"] forState:UIControlStateNormal];
        [_commentButton setImage:[UIImage imageNamed:@"chat_publish_s.png"] forState:UIControlStateHighlighted];
        [_commentButton addTarget:self action:@selector(respondsToCommentBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _commentButton;
}
- (UIButton *)expressionButton {
    if (!_expressionButton) {
        _expressionButton = [[UIButton alloc] init];
        [_expressionButton setImage:[UIImage imageNamed:@"chat_face.png"] forState:UIControlStateNormal];
        [_expressionButton setImage:[UIImage imageNamed:@"chat_face_s.png"] forState:UIControlStateHighlighted];
        [_expressionButton addTarget:self action:@selector(respondsToExpressionButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _expressionButton;
}
- (NSArray *)emojiArray {
    if (!_emojiArray) {
        _emojiArray = [Emoji allEmoji];
    }
    return _emojiArray;
}
- (AVAudioRecorder *)audioRecorder {
    if (!_audioRecorder) {
        //创建录音文件保存路径
        NSURL *url=[self getSavePath];
        //创建录音格式设置
        NSDictionary *setting=[self getAudioSetting];
        //创建录音机
        NSError *error=nil;
        _audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES
        if (error) {
            NSLog(@"创建录音机对象时发生错误，错误信息：%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioRecorder;
}

@end
